//
//  RDDataParser.m
//  eCourseApp
//
//  Created by 飞猪 on 2018/8/26.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "RDDataParser.h"

@implementation RDDataParser

- (void)parseChapterFromBook:(NSString *)path completeHandler:(ChapterBlock)chapterBlock {}

- (NSAttributedString *)attributedStringFromChapterModel:(RDChapterModel *)chapter config:(RDConfiguration *)config {
  return nil;
}

- (void)cutPageWith:(NSAttributedString *)attrString config:(RDConfiguration *)config completeHandler:(PageBlock)pageBlock {
  
  DTCoreTextLayouter *layouter = [[DTCoreTextLayouter alloc] initWithAttributedString:attrString];
  CGRect rect = CGRectMake(config.contentFrame.origin.x, config.contentFrame.origin.y, config.contentFrame.size.width, config.contentFrame.size.height - 5);
  DTCoreTextLayoutFrame *layoutFrame = [layouter layoutFrameWithRect:rect range:NSMakeRange(0, attrString.length)];
  
  NSRange pageVisibleRange = [layoutFrame visibleStringRange];
  NSUInteger rangeOffset = pageVisibleRange.location + pageVisibleRange.length;
  NSInteger count = 1;
  
  
  while (rangeOffset <= attrString.length && rangeOffset != 0) {
    RDPageModel *pageModel = [[RDPageModel alloc] init];
    pageModel.attributedString = [attrString attributedSubstringFromRange:pageVisibleRange];
    pageModel.range = pageVisibleRange;
    pageModel.pageIndex = count - 1;
    
    DTCoreTextLayoutFrame *frame = [layouter layoutFrameWithRect:rect range:NSMakeRange(rangeOffset, attrString.length - rangeOffset)];
    pageVisibleRange = [frame visibleStringRange];
    
    
    if (NSEqualRanges(pageVisibleRange, NSMakeRange(0, 0))) {
      rangeOffset = 0;
    }
    else {
      rangeOffset = pageVisibleRange.location + pageVisibleRange.length;
    }
    
    BOOL completed = (rangeOffset <= attrString.length && rangeOffset != 0) ? false : true;
    
    if (pageBlock) {
      pageBlock(count, pageModel, completed);
    }
    
    count += 1;
  }
  
}

@end
